import React, { useEffect, useState } from 'react'
import Recharge from './components/Recharge'
import Taro from '@tarojs/taro';
import SelectAccount from './components/SelectAccount'
import DatePickerWeek from "@/components/FormCondition/WeepProps";
import { getCurrentInstance, useReachBottom } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components';
import Router from '@/utils/router'
import Tabbar from '@/components/Tabbar'
import dayjs from 'dayjs'
import { fetchListTeacherForCustomer, fetchTeacherScheduleDateForCustomer } from '@/server/shop'
import PaginationComponent from '@/components/ScrollView'
import { backgroundObj, onlineCheckFun } from '@/utils/utils'
import router from '@/utils/router'
import OrganizationEmpty from "@/components/OrganizationEmpty";
import { fetchListSubjectForCustomer } from '@/server/shop'
import DrawerLost from '@/components/DrawerLost'
import Empty from '@/components/Empty'
import './index.scss'
const SubjectQa = (props) => {
    const [list, setList] = useState([])
    const [visible1, setVisible1] = useState(false)
    const fetchListSubject = () => {
        fetchListSubjectForCustomer().then(val => {
            const { subjectList } = val
            setList(subjectList)
        })
    }
    useState(() => {
        fetchListSubject()
    }, [])
    const changeSubject = (value) => {
        onlineCheckFun({
            qaType: 'subject',
            subjectId: value.id,
        }).then(val => {
            const { scheduleDateId, onlineStatus } = val
            if (onlineStatus === '0') {
                setVisible1({
                    show: true,
                    detail: val,
                    onlineType: 'subject',
                    subjectName: value.subjectName,
                    subjectId: value.id,

                })
            } else {
                Router('submitReservation', {
                    args: {
                        subjectName: value.subjectName,
                        id: scheduleDateId,
                        subjectId: value.id,
                        qaType: 'subject'
                    }
                })
            }

        })
    }
    return <View>
        <View className='QuestionCenter_body_title'>
            <View className='QuestionCenter_body_titleLeft'>
                学科答疑
            </View>
            <View onClick={() => { Router('QuestionQa') }} className='QuestionCenter_body_titleRight'>答疑规则</View>
        </View>
        <Empty list={list}>
            {list.map(val => {
                const { subjectName, id } = val
                return <View onClick={() => {
                    changeSubject(val)
                    // Router('submitReservation', { args: { type: 'subjectOnline', id } })
                }} className='QuestionCenter_body_list' >
                    <View className='QuestionCenter_body_item'>
                        <View className='QuestionCenter_body_profile' style={{ ...backgroundObj(val.cover), borderRadius: 8 }}></View>
                        <View className='QuestionCenter_body_content'>
                            <View className='QuestionCenter_bodyitem_title'>{subjectName}</View>
                        </View>
                        <View className='QuestionCenter_bodyitem_button'>发起答疑</View>
                    </View>
                </View>
            })}
        </Empty>

        <DrawerLost visible={visible1} online={'subject'} show={visible1} onClose={() => setVisible1(false)}></DrawerLost>
    </View>
}
const ExaminationQa = (props) => {
    const { title, type = '' } = props
    let qaTypes = ''
    if (type === 'teacher') {
        qaTypes = 'teacherOnline,teacherOffline'
    }
    else {
        qaTypes = 'recruitmentOnline,recruitmentOffline'
    }
    const fetchMockData = async (pageNum, pageSize) => {

        const data = await fetchListTeacherForCustomer({
            page: pageNum,
            limit: pageSize,
            qaTypes
        })
        return new Promise((res, rel) => {
            const {
                teacherList,
                total
            } = data

            res({
                list: teacherList,
                total: total
            })
            rel({
                list: [],
                total: 0
            })
        })

    }
    return <View>
        <View className='QuestionCenter_body_title'>
            <View className='QuestionCenter_body_titleLeft'>
                {title}
            </View>
            <View onClick={() => { Router('QuestionQa') }} className='QuestionCenter_body_titleRight'>答疑规则</View>
        </View>
        <View className='QuestionCenter_body_list'>
            <PaginationComponent
                containerStyle={{ height: `calc(100vh - ${Taro.pxTransform(600)})` }}
                fetchData={fetchMockData}
                renderItem={(item, index) => {
                    const {
                        adminName,
                        teacherName,
                        tagNames = '',
                        profile,
                        description,
                        onlineStatus,
                        teacherSubjectList = [],
                        id
                    } = item
                    const tagNamesList = tagNames.split(',').filter(val => {
                        return val
                    })
                    return <View onClick={() => router('taskQa', {
                        args: {
                            teacherId: id,
                            qaTypes: qaTypes,
                            title: '找老师答疑'
                        }
                    })} className='ExaminationQa_box'>
                        <View className='ExaminationQa_left_box'>
                            <View style={backgroundObj(profile)} className='ExaminationQa_left_profile'>

                            </View>
                            <View className='ExaminationQa_left_tagBox ExaminationQa_left_tagColor1'>
                                {onlineStatus === '1' ? '在线' : '离线'}
                            </View>
                        </View>
                        <View className='ExaminationQa_right_content'>
                            <View className='ExaminationQa_right_titleBox'>
                                <View className='ExaminationQa_right_title font_hide'> {teacherName}</View>
                                {teacherSubjectList.map(item => {
                                    const { subjectName, color } = item
                                    return <View style={{ background: color }} className='ExaminationQa_subjuct'>{subjectName}</View>
                                })}
                                {tagNamesList.map((item, index) => {
                                    return <View key={index} className='ExaminationQa_subjuctTagBox'>
                                        {item}
                                    </View>
                                })}
                            </View>
                            <View className='ExaminationQa_right_desc font_noHide'>{description}</View>
                        </View>
                    </View>
                }}
                keyExtractor={item => item.id.toString()}
            // emptyComponent={<View className="custom-empty">自定义空状态</View>}
            />
        </View>
    </View>
}
const ExaminationQaIF = (props) => {
    const { title, type = '' } = props
    let qaTypes = ''
    if (type === 'teacher') {
        qaTypes = 'teacherOnline,teacherOffline'
    }
    else {
        qaTypes = 'recruitmentOnline,recruitmentOffline'
    }
    const fetchMockData = async (pageNum, pageSize) => {

        const data = await fetchListTeacherForCustomer({
            page: pageNum,
            limit: pageSize,
            qaTypes
        })
        return new Promise((res, rel) => {
            const {
                teacherList,
                total
            } = data

            res({
                list: teacherList,
                total: total
            })
            rel({
                list: [],
                total: 0
            })
        })

    }
    return <View>
        <View className='QuestionCenter_body_title'>
            <View className='QuestionCenter_body_titleLeft'>
                {title}
            </View>
            <View onClick={() => { Router('QuestionQa') }} className='QuestionCenter_body_titleRight'>答疑规则</View>
        </View>
        <View className='QuestionCenter_body_list'>
            <PaginationComponent
                containerStyle={{ height: `calc(100vh - ${Taro.pxTransform(600)})` }}
                fetchData={fetchMockData}
                renderItem={(item, index) => {
                    const {
                        adminName,
                        teacherName,
                        tagNames = '',
                        profile,
                        description,
                        onlineStatus,
                        teacherSubjectList = [],
                        id
                    } = item
                    const tagNamesList = tagNames.split(',').filter(val => {
                        return val
                    })
                    return <View onClick={() => router('taskQa', {
                        args: {
                            teacherId: id,
                            qaTypes: qaTypes,
                            title: '招考答疑'
                        }
                    })} className='ExaminationQa_box'>
                        <View className='ExaminationQa_left_box'>
                            <View style={backgroundObj(profile)} className='ExaminationQa_left_profile'>

                            </View>
                            <View className='ExaminationQa_left_tagBox ExaminationQa_left_tagColor1'>
                                {onlineStatus === '1' ? '在线' : '离线'}
                            </View>
                        </View>
                        <View className='ExaminationQa_right_content'>
                            <View className='ExaminationQa_right_titleBox'>
                                <View className='ExaminationQa_right_title font_hide'> {teacherName}</View>
                                {teacherSubjectList.map(item => {
                                    const { subjectName, color } = item
                                    return <View style={{ background: color }} className='ExaminationQa_subjuct'>{subjectName}</View>
                                })}
                                {tagNamesList.map((item, index) => {
                                    return <View key={index} className='ExaminationQa_subjuctTagBox'>
                                        {item}
                                    </View>
                                })}
                            </View>
                            <View className='ExaminationQa_right_desc font_noHide'>{description}</View>
                        </View>
                    </View>
                }}
                keyExtractor={item => item.id.toString()}
            // emptyComponent={<View className="custom-empty">自定义空状态</View>}
            />

        </View>

    </View>
}
const OfflineQA = (props) => {
    const [params, setParams] = useState({
        scheduleStartDate: dayjs().format('YYYY-MM-DD'),
        scheduleEndDate: dayjs().endOf('week').format('YYYY-MM-DD'),
    })
    const [CheckDate, setCheckDate] = useState(dayjs().format('YYYY-MM-DD'))
    const [list, setList] = useState([])
    const { scheduleStartDate, scheduleEndDate } = params
    const fetchMockData = async (pageNum, pageSize) => {
        const data = await fetchTeacherScheduleDateForCustomer({
            page: 1,
            limit: 9999,
            qaTypes: 'offlineQa',
            scheduleStartDate,
            scheduleEndDate,
        })
        const {
            teacherScheduleDateList = []
        } = data
        setList(teacherScheduleDateList)
    }
    useEffect(() => {
        fetchMockData()
    }, [scheduleStartDate, scheduleEndDate])
    const filterList = () => {
        return list.filter(val => {
            return val.scheduleDate === CheckDate
        })
    }
    const onChange = (item) => {
        const { orderStatus = '0', id, orderSn, qaType } = item
        if (orderStatus === '-1') {
            Router('SubmitOrder', {
                orderSn,
                userOfflineQaId,
                qaType
            })
        }
        else if (orderStatus !== '1') {
            router('seatReservation', {
                args: {
                    id: id,
                    scheduleStartDate,
                    scheduleEndDate,
                    otherStatus: orderStatus
                }
            })
        }
        else {
            router('SeatReservationRead', {
                args: {
                    id: id,
                    scheduleStartDate,
                    scheduleEndDate,
                    otherStatus: orderStatus
                }
            })
        }
    }
    return <View>
        <View className='QuestionCenter_body_title'>
            <View className='QuestionCenter_body_titleLeft'>
                线下答疑课
            </View>
            <View onClick={() => {
                Router('QuestionQa')
            }} className='QuestionCenter_body_titleRight'>答疑规则</View>
        </View>
        <View className='QuestionCenter_body_list'>
            <View className='OfflineQA_box'>
                <View className='OfflineQA_time_select'>
                    <DatePickerWeek list={list} onChange={(e) => {
                        setCheckDate(e)
                    }}></DatePickerWeek>
                </View>
                <View>
                    {filterList().map((item, index) => {
                        const { orderStatus = '0', fullAddress, title, orderUserAmount, scheduleDate, startTime, endTime, priceType, price, maxStudentAmount, remainAmount, campusName, classroomName, subjectList = [], teacherList = [], id } = item
                        const renderBtn = () => {
                            if (orderStatus === '-1') {
                                return <View className="OfflineQA_userbtn">
                                    待付款
                                </View>
                            }
                            if (orderStatus === '0') {
                                return <View className="OfflineQA_userbtn">
                                    预约
                                </View>
                            } else if (orderStatus === '1') {
                                return <View className="OfflineQA_userbtn OfflineQA_btnStatus3">
                                    已预约
                                </View>
                            } else if (orderStatus === '2') {
                                return <View className="OfflineQA_userbtn OfflineQA_btnStatus2">
                                    已取消
                                </View>
                            }
                            else if (orderStatus === '3') {
                                return <View className="OfflineQA_userbtn OfflineQA_btnStatus2">
                                    已约满
                                </View>
                            }
                            else if (orderStatus === '4') {
                                return <View className="OfflineQA_userbtn OfflineQA_btnStatus3">
                                    答疑中
                                </View>
                            } else if (orderStatus === '5') {
                                return <View className="OfflineQA_userbtn OfflineQA_btnStatus2">
                                    不可约
                                </View>
                            }


                        }
                        return <View key={index} onClick={() => {
                            onChange(item)
                        }} className="OfflineQA_list">
                            <View className="OfflineQA_title">
                                {subjectList.map(val => {
                                    const { color, subjectName } = val
                                    return <View style={{ background: color }} className='ExaminationQa_subjuct'>{subjectName}</View>
                                })}
                                <View className="OfflineQA_title_font font_hide">{title}</View>
                                <View className="OfflineQA_title_status OfflineQA_title_statusColor2">
                                    {priceType === 'free' ? '免费' : ' ￥' + price}
                                </View>
                            </View>
                            <View className="OfflineQA_count">
                                可预约数：{maxStudentAmount} <Text className='OfflineQA_count_Text'>当前剩余{remainAmount}</Text>
                            </View>
                            <View className="OfflineQA_address">
                                答疑地址： {fullAddress}
                            </View>
                            <View className="OfflineQA_room">
                                答疑教室：{campusName + classroomName}
                            </View>
                            <View className="OfflineQA_time">
                                答疑时间：{scheduleDate} {startTime}-{endTime}
                            </View>
                            <View className="OfflineQA_userBox">
                                <View className="OfflineQA_userProfile">
                                    {teacherList.map(val => {
                                        const { profile, teacherName } = val
                                        return <View>
                                            <View style={backgroundObj(profile)} className="OfflineQA_userProfileBox"></View>
                                            <View className="OfflineQA_username">{teacherName}</View>
                                        </View>
                                    })}
                                </View>
                                <View style={{ display: 'flex', alignItems: 'center' }}>
                                    {renderBtn()}
                                </View>
                            </View>
                        </View>
                    })}
                </View>
            </View>

        </View>

    </View>
}
const QuestionCenter = (props) => {
    const { active: defaultActive = '0' } = getCurrentInstance().router.params
    const [visible, setVisible] = useState(false)
    const [visible1, setVisible1] = useState(false)
    const [active, setActive] = useState(defaultActive)

    const list = [
        {
            label: '学科答疑',
            value: '学科知识在线答疑',
            iconClass: 'QuestionCenter_center_iconStyle1',
            key: '0'
        },
        {
            label: '找老师',
            value: '指定学科老师在线/线下答疑',
            iconClass: 'QuestionCenter_center_iconStyle2',
            key: '1'
        },
        {
            label: '招考专区答疑',
            value: '升学专业指导老师1V1在线/线下答疑',
            iconClass: 'QuestionCenter_center_iconStyle3',
            key: '2'
        },
        // {
        //     label: '线下答疑课',
        //     value: '学科线下答疑课预约入口',
        //     iconClass: 'QuestionCenter_center_iconStyle4',
        //     key: '3',
        // },

    ]

    const RenderContent = {
        0: <SubjectQa setVisible1={setVisible1} visible={visible1}></SubjectQa>,
        1: <ExaminationQa type='teacher' title={'找老师'}></ExaminationQa>,
        2: <ExaminationQaIF type='recruitment' title={'招考专区答疑'}></ExaminationQaIF>,
        3: <OfflineQA></OfflineQA>
    }[active]
    return <View className='QuestionCenter_box'>
        <Tabbar background={'transparent'} title='答疑中心'></Tabbar>
        <View className='QuestionCenter_center_box'>
            {list.map((item) => {
                const { label, value, key, iconClass } = item
                return <View onClick={(e) => {
                    setActive(key)
                }} className={`QuestionCenter_center_item  ${key === active ? 'QuestionCenter_center_select' : ''}`}>
                    <View className='QuestionCenter_center_title'>{label}</View>
                    <View className='QuestionCenter_center_desc'>{value}</View>
                    <View className={iconClass}></View>
                </View>
            })}
        </View>
        {RenderContent}
        <SelectAccount show={visible1} onClose={() => { setVisible1(false) }}></SelectAccount>
        <Recharge show={visible} onClose={() => { setVisible(false) }}></Recharge>
    </View>
}
const OrganizationTool = (props) => {
    return <OrganizationEmpty Tool={QuestionCenter} title='请先选择机构再查看答疑'>
    </OrganizationEmpty>
}
export default OrganizationTool